package com.century.sjt.activity.login;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.R;
import com.century.sjt.SjtApplication;
import com.century.sjt.SjtHelper;
import com.century.sjt.activity.BaseActivity;
import com.century.sjt.activity.Forget_pwdActivity;
import com.century.sjt.activity.MainActivity;
import com.century.sjt.util.Base64Utils;
import com.century.sjt.util.Code;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.utils.PreferenceManager;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.century.sjt.EMChat.utils.EaseCommonUtils;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by 炳基 on 2016/8/11.
 * 登陆
 */
public class LoginActivity extends BaseActivity {
    private static final String TAG = "LoginActivity";
    @BindView(R.id.icon_position)
    TextView icon_position;
    @BindView(R.id.icon_jump)
    TextView icon_jump;
    @BindView(R.id.icon_phone)
    TextView icon_phone;
    @BindView(R.id.icon_password)
    TextView icon_password;
    @BindView(R.id.icon_eye)
    TextView icon_eye;
    @BindView(R.id.icon_global)
    TextView icon_global;
    @BindView(R.id.login_bg)
    RelativeLayout layout_bg;
    @BindView(R.id.login_username)
    EditText usernameEditText;
    @BindView(R.id.login_password)
    EditText passwordEditText;
    @BindView(R.id.login_layout_forge)
    LinearLayout layout_ForgetPwd;
    @BindView(R.id.login_layout_register)
    LinearLayout layout_Register;
    @BindView(R.id.layout_country)
    LinearLayout layout_Country;
    @BindView(R.id.country)
    TextView tvCountryName;
    @BindView(R.id.country_code)
    TextView tvCountryCode;
    @BindView(R.id.choose_language)
    LinearLayout choose_language;

    public static final int REQUEST_CODE_SETNICK = 1;
    private boolean progressShow;
    private boolean autoLogin = false;

    private String currentUsername;
    private String currentPassword;

    public static SharedPreferences mainSharedPreferences;
    private ImageView ivCode;
    private EditText etCode;
    private Code code;
    private TipUtil tipUtil;
    private String userId;
    private String mobile;
    private String mobileCode = null;
    private boolean isSeePwd=false;
    @Override
    protected void onCreate(Bundle arg0) {
        setContentView(R.layout.activity_login);
        super.onCreate(arg0);
        //透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);//软键盘设置

        initView();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        // 如果登录成功过，直接进入主页面
        if (SjtHelper.getInstance().isLoggedIn()) {
            autoLogin = true;
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            return;
        }

        mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
        tvCountryName.setText(PreferenceManager.getInstance().getCountryName());
        mobileCode = PreferenceManager.getInstance().getMobileCode();
        tvCountryCode.setText("+" + mobileCode);
        layout_Country.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(LoginActivity.this, ChooseCountryActivity.class);
                intent.putExtra("type","login");
                startActivityForResult(intent,Constant.REQUESTCODE_COUNTRY);
            }
        });
        choose_language.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(LoginActivity.this, ChooseLanguageActivity.class);
                intent.putExtra("type","login");
                startActivityForResult(intent,Constant.REQUESTCODE_LANGUAGE);
            }
        });
        layout_ForgetPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(LoginActivity.this, Forget_pwdActivity.class);
                startActivity(intent);
            }
        });
        //注册
        layout_Register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });
        // 如果用户名改变，清空密码
        usernameEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                passwordEditText.setText(null);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        if (SjtHelper.getInstance().getCurrentMobile() != null) {
            usernameEditText.setText(SjtHelper.getInstance().getCurrentMobile());
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode==RESULT_OK){
            switch (requestCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK
                case Constant.REQUESTCODE_COUNTRY:
                    Bundle bundle = data.getExtras();
                    String str = bundle.getString("countryName");//str即为回传的值
                    mobileCode = bundle.getString("mobileCode");
                    tvCountryName.setText(str);
                    tvCountryCode.setText("+" + mobileCode);
                    usernameEditText.setText("");
                    passwordEditText.setText("");
                    break;
                case Constant.REQUESTCODE_LANGUAGE:

                    break;
                default:
                    break;
        }

        }

        super.onActivityResult(requestCode, resultCode, data);
    }
    @Override
    protected void initEvent() {
        Typeface iconfont = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        icon_position.setTypeface(iconfont);
        icon_phone.setTypeface(iconfont);
        icon_jump.setTypeface(iconfont);
        icon_password.setTypeface(iconfont);
        icon_eye.setTypeface(iconfont);
        icon_global.setTypeface(iconfont);
        hideSoftKeyboard();
        icon_eye.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                TipUtil.showToast("点击", RegisterActivity.this, 1);
                if (isSeePwd){
                    isSeePwd=false;
                }else {
                    isSeePwd=true;
                }
                if(isSeePwd){
                    //如果选中，显示密码
                    icon_eye.setText(getString(R.string.icon_eyes_closed));
//                    Log.e("main","1");
                    passwordEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }else{
                    //否则隐藏密码
                    icon_eye.setText(getString(R.string.icon_eye));
//                    Log.e("main","2");
                    passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }

            }
        });
    }
    @Override
    protected void initData() {

    }

    /**
     * 登录
     *
     * @param view
     */
    public void login(View view) {

        final String strPhone = usernameEditText.getText().toString();
        final String strPassword = passwordEditText.getText().toString();
        if (strPhone == null || strPhone.trim().equals("")) {
            TipUtil.showToast(getResources().getString(R.string.error_no_phone), LoginActivity.this, 1);
        } else if (strPassword == null || strPassword.trim().equals("")) {
            TipUtil.showToast(getResources().getString(R.string.enter_a_password), LoginActivity.this, 1);
        } else if (strPassword.length()<6 || strPassword.length()>16){
            TipUtil.showToast(getResources().getString(R.string.error_isno_6or16_password), LoginActivity.this, 1);
        }else {
            //显示Progress Dialog
            TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), LoginActivity.this);
            //加密密码
            byte[] encodePwd = strPassword.getBytes();
            final String epwd = Base64Utils.encode(encodePwd);
            //1.传送方式              //2.地址                 //3.获取成功
            StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.LoginUserHost, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    TipUtil.log("登录接口返回", response, 1);
//                    TipUtil.closeProgressDialog();
                    try {
                        JSONTokener jsonParser = new JSONTokener(response);
                        JSONObject res = (JSONObject) jsonParser.nextValue();
                        String message = res.getString("message");
                        String code = res.getString("code");
                        if (code.equals("200")) {//手机号码已经存在了
//                            TipUtil.showToast(getResources().getString(R.string.login_success), LoginActivity.this, 1);
//                                        Log.v("sjt",sysId);
                            //将手机、昵称和图标的id存入sharePreference
                            String data = res.getString("data");
                            JSONTokener jsonParser1 = new JSONTokener(data);
                            JSONObject dataJo = (JSONObject) jsonParser1.nextValue();
                            String birthday = dataJo.getString("birthday");
                            String idCard = dataJo.getString("idCard");
                            String nickName = dataJo.getString("nickName");
                            String name = dataJo.getString("name");
                            userId = dataJo.getString("userId");
                            String inviteCode = dataJo.getString("inviteCode");
                            String inviteUrl=dataJo.getString("inviteUrl");
                            String gender = dataJo.getString("gender");
                            String image = dataJo.getString("image");
                            String isRealName = dataJo.getString("isRealName");
                            String nativeAddr = dataJo.getString("nativeAddr");
                            mobile = dataJo.getString("mobile");
                            String isCashPwdSet = dataJo.getString("isCashPwdSet");
                            String isMerchant=dataJo.getString("isMerchant");
                            String isShop=dataJo.getString("isShop");
                            String whatsUp = dataJo.getString("whatsUp");
                            String mobileCode = dataJo.getString("mobileCode");
                            String isTrans = dataJo.getString("isTrans");//是否开通翻译
                            String transLanguage = dataJo.getString("transLanguage");//翻译语言
                            int level = dataJo.getInt("level");
                            SharedPreferences.Editor editor = LoginActivity.mainSharedPreferences.edit();
                            editor.putString("birthday", birthday);
                            editor.putString("idCard", idCard);
                            editor.putString("nickName", nickName);
                            editor.putString("name", name);
                            editor.putString("userId", userId);
                            editor.putString("inviteCode", inviteCode);
                            editor.putString("inviteUrl",inviteUrl);
                            editor.putString("gender", gender);
                            editor.putString("image", image);
                            editor.putString("whatsUp",whatsUp);
                            editor.putString("isRealName", isRealName);
                            editor.putString("nativeAddr", nativeAddr);
                            editor.putString("mobile", mobile);
                            editor.putString("isCashPwdSet", isCashPwdSet);
                            editor.putString("isLogin", "1");
                            editor.putString("isMerchant",isMerchant);
                            editor.putString("isShop",isShop);
                            editor.putInt("level",level);
                            editor.putString("mobileCode",mobileCode);
                            //如果是商店，就获取商店ID
                            if("1".equals(isShop)) {
                                String shopId = dataJo.getString("shopId");
                                int shopLevel = dataJo.getInt("shopLevel");
                                editor.putString("shopId", shopId);
                                editor.putInt("shopLevel",shopLevel);
                            }
                            //翻译
                            editor.putString("transLanguage",transLanguage);
                            editor.putString("isTrans",isTrans);
                            editor.commit();

                            emLogin(1);//环信登录

                        } else {
                            //关闭进度条
                            TipUtil.closeProgressDialog();
//                            TipUtil.showToast(getResources().getString(R.string.login_defeat), LoginActivity.this, 1);
                            TipUtil.showToast(message, LoginActivity.this, 1);
                        }
                    } catch (Exception ex) {
                        //关闭进度条
                        TipUtil.closeProgressDialog();
                        TipUtil.showToast(getResources().getString(R.string.error_service), LoginActivity.this, 1);
                    }
                }
            }, new Response.ErrorListener() {            //4.获取失败
                @Override
                public void onErrorResponse(VolleyError error) {
                    //关闭进度条
                    TipUtil.closeProgressDialog();
                    TipUtil.showToast(getResources().getString(R.string.error_network), LoginActivity.this, 1);
                }
            }) {
                @Override
                //传送出去的参数
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("mobile", strPhone.trim());
                    map.put("password", epwd.trim());
                    map.put("mobileCode",mobileCode);
                    map.put("language",PreferenceManager.getInstance().getLanguageCode());
                    return map;
                }

                @Override
                protected Response<String> parseNetworkResponse(NetworkResponse response) {
                    try {
                        Log.e("sjt", "登录：get headers in parseNetworkResponse " + response.headers.toString());

                        SharedPreferences.Editor editor = LoginActivity.mainSharedPreferences.edit();
                        String mHeader = response.headers.toString();
                        String cookieFromResponse = "";
                        Pattern pattern = Pattern.compile("Set-Cookie.*?;");
                        Matcher m = pattern.matcher(mHeader);
                        if (m.find()) {
                            cookieFromResponse = m.group();
//                                    Log.w("LOG","cookie from server "+ cookieFromResponse);
//                                    cookieFromResponse = cookieFromResponse.substring(28, cookieFromResponse.length() - 1);
                            cookieFromResponse = cookieFromResponse.substring(11, cookieFromResponse.length() - 1);
//                                    Log.w("LOG","cookie from server "+ cookieFromResponse);
//                                    Map<String, String> responseHeaders = response.headers;
//                                    String rawCookies = responseHeaders.get("Set-Cookie").toString();
//                                    String cookievalue = rawCookies.substring(0,rawCookies.length()-33);
//                                    Log.d("sjt","rawCookies="+rawCookies+" cookievalue:"+cookievalue);
////                                    String dataString = new String(response.data, "UTF-8");
                        }
                        //rememberMe------20150623
                        Pattern pattern1 = Pattern.compile("rememberMe.*?;");
                        Matcher m1 = pattern1.matcher(mHeader);
                        List<String> rememberlist = new ArrayList<>();
                        while (m1.find()) {
                            String rememberMe = m1.group(0);
                            rememberlist.add(rememberMe);
                        }
                        String rememberMeValue = "";
                        if (rememberlist.size() > 1) {
                            rememberMeValue = rememberlist.get(1);
                            Log.e("value", rememberMeValue);
                        }
                        editor.putString("cookie", cookieFromResponse);
                        editor.putString("rememberMe", rememberMeValue);
                        editor.commit();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //使用正则表达式从reponse的头中提取cookie内容的子串
                    return super.parseNetworkResponse(response);
                }
            };
            stringRequest.setRetryPolicy(new DefaultRetryPolicy(20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

            mQueue.add(stringRequest);
        }

    }

    /**
     * EM登录
     */
    public void emLogin(final int time) {
        if (!EaseCommonUtils.isNetWorkConnected(this)) {
            Toast.makeText(this, R.string.network_isnot_available, Toast.LENGTH_SHORT).show();
            return;
        }
        currentUsername = userId.trim();
        currentPassword = passwordEditText.getText().toString().trim();

        if (TextUtils.isEmpty(currentUsername)) {
            Toast.makeText(this, R.string.User_name_cannot_be_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(currentPassword)) {
            Toast.makeText(this, R.string.Password_cannot_be_empty, Toast.LENGTH_SHORT).show();
            return;
        }

//        progressShow = true;
//        final ProgressDialog pd = new ProgressDialog(LoginActivity.this);
//        pd.setCanceledOnTouchOutside(false);
//        pd.setOnCancelListener(new DialogInterface.OnCancelListener() {
//
//            @Override
//            public void onCancel(DialogInterface dialog) {
//                progressShow = false;
//            }
//        });
//        pd.setMessage(getString(R.string.Is_landing));
//        pd.show();

        final long start = System.currentTimeMillis();
        // 调用sdk登陆方法登陆聊天服务器
        EMChatManager.getInstance().login(currentUsername, "111111", new EMCallBack() {

            @Override
            public void onSuccess() {
//                if (!progressShow) {
//                    return;
//                }

                // 登陆成功，保存用户名
//                SjtHelper.getInstance().setCurrentUserName(currentUsername);
//                SjtHelper.getInstance().setCurrentMobile(mobile);
                // 注册群组和联系人监听
                SjtHelper.getInstance().registerGroupAndContactListener();

                // ** 第一次登录或者之前logout后再登录，加载所有本地群和回话
                // ** manually load all local groups and
                EMGroupManager.getInstance().loadAllGroups();
                EMChatManager.getInstance().loadAllConversations();

                // 更新当前用户的nickname 此方法的作用是在ios离线推送时能够显示用户nick
                boolean updatenick = EMChatManager.getInstance().updateCurrentUserNick(
                        SjtApplication.currentUserNick.trim());
                if (!updatenick) {
                    Log.e("LoginActivity", "update current user nick fail");
                }
                //异步获取当前用户的昵称和头像(从自己服务器获取，demo使用的一个第三方服务)
                // TODO异步获取当前用户的昵称和头像(从自己服务器获取，demo使用的一个第三方服务
//                SjtHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();

//                if (!LoginActivity.this.isFinishing() && pd.isShowing()) {
//                    pd.dismiss();
//                }
                TipUtil.closeProgressDialog();
                // 进入主页面
//                Intent intent = new Intent(LoginActivity.this,
//                        MainActivity.class);
//                startActivity(intent);
                startActivity(new Intent(LoginActivity.this,
                        MainActivity.class).putExtra("id","loging"));
                finish();
            }

            @Override
            public void onProgress(int progress, String status) {
            }

            @Override
            public void onError(final int code, final String message) {
                TipUtil.log("登录返回", code + "+" + message, 1);
//                if (!progressShow) {
//                    return;
//                }
                runOnUiThread(new Runnable() {
                    public void run() {
//                        pd.dismiss();
                        TipUtil.closeProgressDialog();
                        if (time == 1) {
                            if (code == -1005) {
//                                emRegister(currentUsername);//em注册
                            }else {
                                Toast.makeText(getApplicationContext(), getString(R.string.Login_failed) + message,
                                        Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(getApplicationContext(), getString(R.string.Login_failed) + message,
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (autoLogin) {

            return;
        }
        passwordEditText.setText(null);
        String language = PreferenceManager.getInstance().getCurrentLanguage();
        if ("".equals(language)||null==language){
            startActivity(new Intent(LoginActivity.this, ChooseCountryButtonActivity.class));
        }
    }

}
